/**
* @author: mayabo
* @date: 2021-11-02
* @description: 人员管理
*/
<template>
  <div class="default-wrap">
    <div class="content-title">
      <TitleCard title="总人数" :count="NUmberInfo.one || 0" />
      <TitleCard title="部门主管" :count="NUmberInfo.two || 0" />
      <TitleCard title="区域主管" :count="NUmberInfo.three || 0" />
      <TitleCard title="区域工作人员" :count="NUmberInfo.four || 0" />
    </div>
    <div class="content-search">
      <div class="search-select">
        <Input v-model="search.userName" placeholder="姓名" clearable></Input>
        <Input v-model="search.loginName" placeholder="用户名" clearable></Input>
        <Select v-model="search.departmentID" placeholder="部门" clearable>
          <Option
            v-for="item in DepartmentLists"
            :value="item.id"
            :key="item.id"
            >{{ item.departmentName }}</Option
          >
        </Select>
        <Select v-model="search.roleID" placeholder="角色" clearable>
          <Option v-for="item in RoleLists" :value="item.id" :key="item.id">{{
            item.roleName
          }}</Option>
        </Select>
        <!-- <Button type="primary" @click="queryList" icon="ios-search"></Button> -->
        <i class="search-icon" @click="queryList"></i>
      </div>
      <div class="search-btn">
        <Button type="primary" @click="openAddUserModel">新增人员</Button>
        <Button type="primary" @click="openRoleModel()">配置角色</Button>
        <Button type="primary" @click="openRolestaticModel()">设置状态</Button>
        <Dropdown style="margin-left: 8px" @on-click="onDropClick">
          <Button type="primary">
            更多
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <Dropdown-menu slot="list">
            <Dropdown-item name="upload">批量导入</Dropdown-item>
          </Dropdown-menu>
        </Dropdown>
      </div>
    </div>

    <div class="content-table">
      <Table
        @on-select="onChangeSelect"
        border
        :columns="columns"
        :data="tableData"
      ></Table>
    </div>
    <div class="content-page">
      <div class="page-btn">
        <Button type="primary" :loading="exportLoading" @click="exportToExcel()">数据导出</Button>
      </div>
      <Page
        :total="listDate.allCount || 0"
        :page-size="search.pageSize"
        :current="search.pageIndex"
        @on-change="changepage"
        @on-page-size-change="_nowPageSize"
        show-elevator
      ></Page>
    </div>

    <userModel :visible="userVisible" @onCloseModel="onCloseModel" />
    <!-- 用户配置角色弹出层 -->
    <user-role-model
      :visible="roleVisible"
      :userID="userId"
      :names="names"
      @closeRoleModel="closeRoleModel"
    />
    <!-- 配置状态弹出框 -->
    <role-static-model
      :visible="roleStaticVisible"
      :userId="userId"
      @closeRolestaticModel="closeRolestaticModel"
    />
    <!-- 用户编辑弹出框 -->
    <userUpdateModel
      :userId="userId"
      :visible="updateVisible"
      @closeupdateModel="closeupdateModel"
    />
  </div>
</template>

<script type="text/jsx">
import TitleCard from './components/TitleCard'
import * as api from '@/api/alarm'
import userModel from './components/userModel'
import userRoleModel from './components/userRoleModel'
import roleStaticModel from './components/userStaticModel'
import userUpdateModel from './components/userUpdateModel'
import {
  deleteUser,
  getUserSearchList,
  getDepartment,
  getRoleList,
  getNumberList,
  getUserList
} from '@/api/system/user.js'
import excel from '@/libs/excel'
export default {
  name: 'Management',
  components: {
    TitleCard,
    userModel,
    userRoleModel,
    roleStaticModel,
    userUpdateModel
  },
  data () {
    let that = this
    return {
      search: {
        pageSize: 10,
        pageIndex: 1,
        userName: '',
        loginName: '',
        departmentID: 0,
        roleID: 0
      },
      names: '',
      exportLoading: false,
      list: [],
      listDate: null,
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '姓名',
          key: 'userName',
          align: 'center'
        },
        {
          title: '用户名',
          key: 'loginName',
          align: 'center'
        },
        {
          title: '部门',
          key: 'department',
          align: 'center',
          render (c, { row, column, index }) {
            return <span>{row.departmentName}</span>
          }
        },
        {
          title: '角色',
          key: 'duty',
          align: 'center',
          render (c, { row, column, index }) {
            return <span>{row.dutyName}</span>
          }
        },
        {
          title: '安全等级',
          key: 'securityLevel',
          align: 'center',
          render (c, { row, column, index }) {
            return <span>{row.securityLevelName }</span>
          }
        },
        {
          title: '状态',
          key: 'securityLevel',
          align: 'center',
          render (c, { row, column, index }) {
            if (row.avality) {
              return <span>有效</span>
            }
            if (!row.avality) {
              return <span>无效</span>
            }
            return <span>锁定</span>
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 140,
          align: 'center',
          render (c, { row, column, index }) {
            return (
              <div class="table-button-wrap">
                <span
                  onClick={() => that.openupdateModel(row)}
                  class="table-btn"
                >
                  编辑
                </span>
                <span
                  onClick={() => that.deleteUserInfo(row.id)}
                  class="table-btn"
                >
                  删除
                </span>
              </div>
            )
          }
        }
      ],
      tableData: [],
      alarmLevelList: [],
      alarmTypeList: [],
      showDetail: false,
      roleVisible: false, // 配置角色是否显示
      userVisible: false, // 用户编辑是否显示
      roleStaticVisible: false, // 配置状态是否显示
      modelType: 'add', // add edit check
      userId: -1,
      userTitle: '新增用户',
      updateVisible: false,
      selectList: [],
      DepartmentLists: [], // 部门下拉
      RoleLists: [],
      NUmberInfo: null
    }
  },
  created () {

  },
  mounted () {
    // 获取预警等级
    api.getAlarmLevel().then((response) => {
      this.alarmLevelList = response.data
    })

    // 获取预警类型
    api.getAlarmType().then((response) => {
      this.alarmTypeList = response.data
    })

    // 获取用户列表
    this.getUserLists()
    // 部门下拉
    this.getDepartmentList()
    // 角色下拉
    this.getRoleList()
    // 获取顶部信息
    this.getNumberList()
  },
  methods: {
    // 获取顶部信息
    getNumberList () {
      let that = this
      getNumberList({ st: 1 }).then((res) => {
        if (res.status === 200) {
          that.NUmberInfo = res.data
        } else {
          that.$Message.warning('请求失败，请联系管理员！')
        }
      })
    },
    // 查询列表
    queryList () {
      // 获取用户列表
      this.getUserLists()
    },
    getRoleList () {
      let that = this
      getRoleList().then((res) => {
        if (res.status === 200) {
          that.RoleLists = res.data
        } else {
          that.$Message.warning('请求失败，请联系管理员！')
        }
      })
    },
    // 获取公司列表
    getDepartmentList () {
      let that = this
      getDepartment().then((res) => {
        if (res.status === 200) {
          that.DepartmentLists = res.data
        } else {
          that.$Message.warning('请求失败，请联系管理员！')
        }
      })
    },
    // 点击，切换页面
    changepage (index) {
      // 储存当前页
      this.search.pageIndex = index
      // 获取用户列表
      this.getUserLists()
    },
    // 每页显示的数据条数
    _nowPageSize (index) {
      // 实时获取当前需要显示的条数
      this.search.pageSize = index
    },
    onChangeSelect (selection) {
      this.selectList = selection
    },
    closeupdateModel () {
      this.updateVisible = false
      this.selectList = []
      this.getUserLists()
    },
    openupdateModel (row) {
      this.userId = row.id
      this.updateVisible = true
    },
    // 获取用户列表
    getUserLists () {
      let that = this
      getUserSearchList(that.search).then((res) => {
        if (res.status === 200) {
          that.tableData = []
          that.listDate = res.data
          // that.tableData = res.data.users;
          that.resetData(res.data.users)
        } else {
          that.$Message.warning('请求失败，请联系管理员！')
        }
      })
    },
    // 重构数据
    // 重构数据
    resetData (data) {
      if (!data) {
        this.tableData = []
        return
      }
      if (data && data.length > 0) {
        let that = this
        data.map((item) => {
          let obj = {
            ...item,
            departmentName: item.department.departmentName,
            dutyName: item.duty.userDuty,
            securityLevelName: item.securityLevel.levelName
          }
          that.tableData.push(obj)
        })
      }
    },
    // 删除用户
    deleteUserInfo (id) {
      let that = this
      deleteUser(id).then((res) => {
        if (res.data === 0) {
          that.$Message.success('删除成功')
          // 获取用户列表
          that.getUserLists()
        } else {
          that.$Message.warning('删除失败')
        }
      })
    },
    onDropClick (name) {
      console.log(name)
    },
    // 打开配置角色弹框
    openRoleModel () {
      if (this.selectList.length === 0) {
        this.$Message.warning('请选择用户')
        return
      }
      if (this.selectList.length === 1) {
        this.userId = this.selectList[0].id
        this.names = this.selectList[0].userName
        this.roleVisible = true
        return
      }
      return this.$Message.warning('请选择一个用户')
    },
    // 关闭配置角色弹框
    closeRoleModel () {
      this.roleVisible = false
      this.userId = -1
      this.selectList = []
      // 获取用户列表
      this.getUserLists()
    },
    // 打开设置状态弹窗
    openRolestaticModel () {
      if (this.selectList.length === 0) {
        return this.$Message.warning('请选择用户')
      }
      if (this.selectList.length === 1) {
        this.userId = this.selectList[0].id
        this.roleStaticVisible = true
        return
      }
      this.roleStaticVisible = false
    },
    // 关闭设置状态弹窗
    closeRolestaticModel () {
      this.roleStaticVisible = false
      this.userId = -1
      this.selectList = []
      // 获取用户列表
      this.getUserLists()
    },
    // 打开用户新增弹窗
    openAddUserModel () {
      this.userTitle = '新增用户'
      this.modelType = 'add'
      this.userVisible = true
    },
    // 关闭用户弹窗
    onCloseModel () {
      this.userVisible = false
      // 获取用户列表
      this.getUserLists()
    },
    exportToExcel () {
      this.exportLoading = true
      getUserList().then(response => {
        let list = response.data.map(item => {
          item.userName = item.userName
          item.loginName = item.loginName
          item.departmentName = item.department.departmentName
          item.dutyName = item.duty.userDuty
          item.securityLevelName = item.securityLevel.levelName
          item.avality = item.avality ? '有效' : '无效'
          return item
        })

        if (list.length) {
          const params = {
            title: ['姓名', '用户名', '部门', '角色', '安全等级', '状态'],
            key: ['userName', 'loginName', 'departmentName', 'dutyName', 'securityLevelName', 'avality'],
            data: list,
            autoWidth: true,
            filename: `人员列表_${Date.now()}`
          }
          excel.export_array_to_excel(params)
        } else {
          this.$Message.info('暂无数据！')
        }
      }).finally(() => {
        this.exportLoading = false
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]))
    }
  }
}
</script>

<style lang="less" scoped>
@import "./styles/index.less";
</style>
